package com.xuzili.wechat.servise.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xuzili.wechat.entity.Weather;
import com.xuzili.wechat.servise.WeatherService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xu
 * @date:2022/8/2118:42
 */
@Service
public class WeatherServiceImpl implements WeatherService {
    @Value("${baidu.ak}")
    private String BAI_DU_APP_KEY;

    @Value("${baidu.district_id}")
    private String DISTRICT_ID;

    @Value("${baidu.data_type}")
    private String DATA_TYPE;


    @Override
    public Weather getWeather() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        map.put("district_id",DISTRICT_ID); // 昆山行政代码
        map.put("data_type",DATA_TYPE);//这个是数据类型
        map.put("ak",BAI_DU_APP_KEY);
        String res = restTemplate.getForObject(
                "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
                String.class,
                map);
        JSONObject json = JSONObject.parseObject(res);
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setWind_class(now.getString("wind_class"));
        weather.setWind_dir(now.getString("wind_dir"));
        return weather;
    }
}
